package zhexian.app.smartcall;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import zhexian.app.smartcall.base.BaseActivity;
import zhexian.app.smartcall.base.Const;
import zhexian.app.smartcall.tools.UploadUtil;
import zhexian.app.smartcall.tools.Utils;

/**
 * @author spring sky<br>
 *         Email :vipa1888@163.com<br>
 *         QQ: 840950105<br>
 *         说明：主要用于选择文件和上传文件操作
 */
public class ChangeAvatarActivity extends BaseActivity implements OnClickListener, UploadUtil.OnUploadProcessListener {

    /***
     * 使用照相机拍照获取图片
     */
    public static final int SELECT_PIC_BY_TAKE_PHOTO = 1;
    /***
     * 使用相册中的图片
     */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;

    /***
     * 从Intent获取图片路径的KEY
     */
    public static final String KEY_PHOTO_URI = "photo_uri";

    /**
     * 选择文件
     */
    public static final int TO_SELECT_PHOTO = 3;
    /**
     * 裁剪文件
     */
    public static final int TO_CROP_PHOTO = 4;
    /**
     * 去上传文件
     */
    protected static final int TO_UPLOAD_FILE = 1;
    /**
     * 上传文件响应
     */
    protected static final int UPLOAD_FILE_DONE = 2;  //
    private static final String TAG = "uploadImage";
    /**
     * 上传初始化
     */
    private static final int UPLOAD_INIT_PROCESS = 4;
    /**
     * 上传中
     */
    private static final int UPLOAD_IN_PROCESS = 5;
    /***
     * 这里的这个URL是我服务器的javaEE环境URL
     */
    private ImageView imageView;
    private TextView uploadImageResult;
    private ProgressBar progressBar;

    private String picPath = null;
    private ProgressDialog progressDialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TO_UPLOAD_FILE:
                    toUploadFile();
                    break;

                case UPLOAD_INIT_PROCESS:
                    progressBar.setMax(msg.arg1);
                    break;
                case UPLOAD_IN_PROCESS:
                    progressBar.setProgress(msg.arg1);
                    break;
                case UPLOAD_FILE_DONE:
                    String result = "响应码：" + msg.arg1 + "\n响应信息：" + msg.obj + "\n耗时：" + UploadUtil.getRequestTime() + "秒";
                    uploadImageResult.setText(result);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }

    };

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_avatar);
        initView();
    }

    /**
     * 初始化数据
     */
    private void initView() {
        Button btnSelectGallery = (Button) this.findViewById(R.id.btn_selectImage);
        Button btnTakePhoto = (Button) this.findViewById(R.id.btn_takePhoto);
        Button uploadButton = (Button) this.findViewById(R.id.btn_uploadAvatar);
        btnSelectGallery.setOnClickListener(this);
        btnTakePhoto.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        imageView = (ImageView) this.findViewById(R.id.imageView);
        uploadImageResult = (TextView) findViewById(R.id.uploadImageResult);
        progressDialog = new ProgressDialog(this);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_selectImage:
                pickPhoto();
                break;
            case R.id.btn_takePhoto:
                takePhoto();
                break;
            case R.id.btn_uploadAvatar:
                if (getAvatarFilePath() != null) {
                    handler.sendEmptyMessage(TO_UPLOAD_FILE);
                } else {
                    Toast.makeText(this, "上传的文件路径出错", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 拍照获取图片
     */
    private void takePhoto() {
        //执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.IMAGE_CAPTURE"
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)));
            startActivityForResult(intent, SELECT_PIC_BY_TAKE_PHOTO);
        } else {
            Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show();
        }
    }

    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == Activity.RESULT_OK) {
            Uri photoUri = null;

            if (requestCode == SELECT_PIC_BY_TAKE_PHOTO) {
                final File file = getTempFile(this);
                photoUri = Uri.fromFile(file);
                handlePhotoUri(photoUri);
                return;
            } else {
                if (intent != null) {
                    photoUri = intent.getData();
                }

                if (photoUri != null) {
                    handlePhotoUri(photoUri);
                } else {
                    Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void handlePhotoUri(Uri picUri) {
        if (picUri == null) {
            Log.e(TAG, "未返回图片，请检查程序逻辑！");
        } else {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), picUri);
                Bitmap scaledBmp = Utils.getScaledBitMap(bitmap, 300, 300);
                imageView.setImageBitmap(scaledBmp);
                saveAvatarFile(scaledBmp);
                // 调用剪切
                    cropImageUri(picUri, 100, 100, TO_CROP_PHOTO);
            } catch (FileNotFoundException e) {
                Log.e("Exception", e.getMessage(), e);
            } catch (IOException e) {
                Log.e("Exception", e.getMessage(), e);
            }
        }
    }

    /**
     * 调用系统功能处理图片剪切
     */
	private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 4);
		intent.putExtra("aspectY", 3);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection

		startActivityForResult(intent, requestCode);
	}
    private File getTempFile(Context context) {
        //it will return /sdcard/image.tmp
        final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
        if (!path.exists()) {
            path.mkdir();
        }
        return new File(path, "image.tmp");
    }

    /**
     * 上传服务器响应回调
     */
    @Override
    public void onUploadDone(int responseCode, String message) {
        progressDialog.dismiss();
        Message msg = Message.obtain();
        msg.what = UPLOAD_FILE_DONE;
        msg.arg1 = responseCode;
        msg.obj = message;
        handler.sendMessage(msg);
    }

    private void toUploadFile() {
        uploadImageResult.setText("正在上传中...");
        progressDialog.setMessage("正在上传文件...");
        progressDialog.show();
        String fileKey = "avatar";
        UploadUtil uploadUtil = UploadUtil.getInstance();
        ;
        uploadUtil.setOnUploadProcessListener(this);  //设置监听器监听上传状态

        String uploadUrl = this.baseApp.getServiceUrl(Const.URL_UPLOAD_AVATAR);
        uploadUrl = String.format(uploadUrl, this.baseApp.getUserName(), this.baseApp.getPassword());
        uploadUtil.uploadFile(getAvatarFilePath(), fileKey, uploadUrl, null);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
        handler.obtainMessage().sendToTarget();
        handler.dispatchMessage(msg);
    }

    @Override
    public void initUpload(int fileSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
        handler.sendMessage(msg);
    }

    /**
     * 把自己的头像保存到本地文件
     *
     * @param bmp 头像bmp
     */
    private void saveAvatarFile(Bitmap bmp) {
        String filePath = getAvatarFilePath();
        File f = new File(filePath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            Toast.makeText(this, "打开头像文件失败", Toast.LENGTH_LONG).show();
        }
    }

    private String getAvatarFilePath() {
        File path = new File(Environment.getExternalStorageDirectory(), this.getPackageName());
        if (!path.exists()) {
            path.mkdir();
        }
        return path.getAbsolutePath() + "/" + "MyAvatar.jpg";
    }
}